/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * POFrame.java
 *
 * Created on Mar 10, 2011, 3:54:20 PM
 */

package gbbmgmt;

import org.jdesktop.application.Action;
import java.util.*;
import javax.swing.JOptionPane;
import javax.swing.table.*;
import java.awt.Point;
import javax.swing.JMenuItem;
//import javax.swing.JPopupMenu;
import java.awt.event.*;
import javax.swing.SwingUtilities;

/**
 *
 * @author dchapman
 */
public class POFrame extends javax.swing.JFrame {

    public ArrayList<String[]> PO;

    public static final int New = 0;
    public static final int Approved = 10;
    public static final int OnOrder = 20;
    public static final int Received = 30;

    public int status = 0;

    public int rowNumDel = 0;

    /** Creates new form POFrame */
    public POFrame() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        jComboBoxPO = new javax.swing.JComboBox();
        jButtonCustFirst = new javax.swing.JButton();
        jButtonCustPrev = new javax.swing.JButton();
        jButtonCustNext = new javax.swing.JButton();
        jButtonCustLast = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabelPOID = new javax.swing.JLabel();
        jButtonExit = new javax.swing.JButton();
        jButtonUpdate = new javax.swing.JButton();
        jButtonNewPO = new javax.swing.JButton();
        jButtonAddLine = new javax.swing.JButton();
        jDateChooser = new com.toedter.calendar.JDateChooser();
        jSeparator2 = new javax.swing.JSeparator();
        jLabel2 = new javax.swing.JLabel();
        jLabelStatus = new javax.swing.JLabel();
        jButtonApprovePO = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTablePO = new javax.swing.JTable();
        jTextFieldSearchVal = new javax.swing.JTextField();
        jButtonSearch = new javax.swing.JButton();
        jButtonProcessPO = new javax.swing.JButton();

        jPopupMenu1.setName("jPopupMenu1"); // NOI18N

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        jComboBoxPO.setName("jComboBoxPO"); // NOI18N
        jComboBoxPO.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
                jComboBoxPOPopupMenuWillBecomeInvisible(evt);
            }
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
            }
        });

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(gbbmgmt.GBBMGMTApp.class).getContext().getActionMap(POFrame.class, this);
        jButtonCustFirst.setAction(actionMap.get("FirstRecord")); // NOI18N
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(gbbmgmt.GBBMGMTApp.class).getContext().getResourceMap(POFrame.class);
        jButtonCustFirst.setText(resourceMap.getString("jButtonCustFirst.text")); // NOI18N
        jButtonCustFirst.setName("jButtonCustFirst"); // NOI18N

        jButtonCustPrev.setAction(actionMap.get("PrevRecord")); // NOI18N
        jButtonCustPrev.setText(resourceMap.getString("jButtonCustPrev.text")); // NOI18N
        jButtonCustPrev.setName("jButtonCustPrev"); // NOI18N

        jButtonCustNext.setAction(actionMap.get("NextRecord")); // NOI18N
        jButtonCustNext.setText(resourceMap.getString("jButtonCustNext.text")); // NOI18N
        jButtonCustNext.setName("jButtonCustNext"); // NOI18N

        jButtonCustLast.setAction(actionMap.get("LastRecord")); // NOI18N
        jButtonCustLast.setText(resourceMap.getString("jButtonCustLast.text")); // NOI18N
        jButtonCustLast.setName("jButtonCustLast"); // NOI18N

        jSeparator1.setName("jSeparator1"); // NOI18N

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jLabelPOID.setText(resourceMap.getString("jLabelPOID.text")); // NOI18N
        jLabelPOID.setName("jLabelPOID"); // NOI18N

        jButtonExit.setAction(actionMap.get("ExitPO")); // NOI18N
        jButtonExit.setText(resourceMap.getString("jButtonExit.text")); // NOI18N
        jButtonExit.setName("jButtonExit"); // NOI18N

        jButtonUpdate.setAction(actionMap.get("UpdatePO")); // NOI18N
        jButtonUpdate.setText(resourceMap.getString("jButtonUpdate.text")); // NOI18N
        jButtonUpdate.setName("jButtonUpdate"); // NOI18N

        jButtonNewPO.setAction(actionMap.get("NewPO")); // NOI18N
        jButtonNewPO.setText(resourceMap.getString("jButtonNewPO.text")); // NOI18N
        jButtonNewPO.setName("jButtonNewPO"); // NOI18N

        jButtonAddLine.setAction(actionMap.get("AddLine")); // NOI18N
        jButtonAddLine.setText(resourceMap.getString("jButtonAddLine.text")); // NOI18N
        jButtonAddLine.setName("jButtonAddLine"); // NOI18N

        jDateChooser.setName("jDateChooser"); // NOI18N

        jSeparator2.setName("jSeparator2"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jLabelStatus.setText(resourceMap.getString("jLabelStatus.text")); // NOI18N
        jLabelStatus.setName("jLabelStatus"); // NOI18N

        jButtonApprovePO.setAction(actionMap.get("ApprovePO")); // NOI18N
        jButtonApprovePO.setText(resourceMap.getString("jButtonApprovePO.text")); // NOI18N
        jButtonApprovePO.setName("jButtonApprovePO"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTablePO.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "#", "Stock Code", "Description", "Vendor", "Vendor P/N", "Qty", "Cost Per", "Ext Cost", "Wearhouse", "Rcvd?"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Float.class, java.lang.Float.class, java.lang.Float.class, java.lang.String.class, java.lang.Boolean.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jTablePO.setName("jTablePO"); // NOI18N
        jTablePO.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTablePOMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTablePO);
        jTablePO.getColumnModel().getColumn(0).setMinWidth(25);
        jTablePO.getColumnModel().getColumn(0).setPreferredWidth(25);
        jTablePO.getColumnModel().getColumn(0).setMaxWidth(25);
        jTablePO.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("jTablePO.columnModel.title9")); // NOI18N
        jTablePO.getColumnModel().getColumn(1).setMinWidth(75);
        jTablePO.getColumnModel().getColumn(1).setPreferredWidth(75);
        jTablePO.getColumnModel().getColumn(1).setMaxWidth(75);
        jTablePO.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("jTablePO.columnModel.title0")); // NOI18N
        jTablePO.getColumnModel().getColumn(2).setPreferredWidth(200);
        jTablePO.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("jTablePO.columnModel.title1")); // NOI18N
        jTablePO.getColumnModel().getColumn(3).setPreferredWidth(100);
        jTablePO.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("jTablePO.columnModel.title2")); // NOI18N
        jTablePO.getColumnModel().getColumn(4).setHeaderValue(resourceMap.getString("jTablePO.columnModel.title3")); // NOI18N
        jTablePO.getColumnModel().getColumn(5).setPreferredWidth(30);
        jTablePO.getColumnModel().getColumn(5).setHeaderValue(resourceMap.getString("jTablePO.columnModel.title4")); // NOI18N
        jTablePO.getColumnModel().getColumn(6).setPreferredWidth(50);
        jTablePO.getColumnModel().getColumn(6).setHeaderValue(resourceMap.getString("jTablePO.columnModel.title5")); // NOI18N
        jTablePO.getColumnModel().getColumn(7).setPreferredWidth(50);
        jTablePO.getColumnModel().getColumn(7).setHeaderValue(resourceMap.getString("jTablePO.columnModel.title6")); // NOI18N
        jTablePO.getColumnModel().getColumn(8).setHeaderValue(resourceMap.getString("jTablePO.columnModel.title7")); // NOI18N
        jTablePO.getColumnModel().getColumn(9).setPreferredWidth(30);
        jTablePO.getColumnModel().getColumn(9).setHeaderValue(resourceMap.getString("jTablePO.columnModel.title8")); // NOI18N

        jTextFieldSearchVal.setText(resourceMap.getString("jTextFieldSearchVal.text")); // NOI18N
        jTextFieldSearchVal.setName("jTextFieldSearchVal"); // NOI18N

        jButtonSearch.setAction(actionMap.get("SearchPO")); // NOI18N
        jButtonSearch.setText(resourceMap.getString("jButtonSearch.text")); // NOI18N
        jButtonSearch.setName("jButtonSearch"); // NOI18N

        jButtonProcessPO.setAction(actionMap.get("ProceessPO")); // NOI18N
        jButtonProcessPO.setText(resourceMap.getString("jButtonProcessPO.text")); // NOI18N
        jButtonProcessPO.setName("jButtonProcessPO"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jComboBoxPO, javax.swing.GroupLayout.PREFERRED_SIZE, 403, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jTextFieldSearchVal, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonSearch)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 89, Short.MAX_VALUE)
                .addComponent(jButtonCustFirst)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonCustPrev)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonCustNext)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonCustLast)
                .addContainerGap())
            .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 901, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabelPOID, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabelStatus)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 469, Short.MAX_VALUE)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addComponent(jSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 901, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButtonUpdate)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonNewPO)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonAddLine)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonApprovePO)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonProcessPO)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 363, Short.MAX_VALUE)
                .addComponent(jButtonExit)
                .addContainerGap())
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 901, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jComboBoxPO, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonCustFirst)
                    .addComponent(jButtonCustPrev)
                    .addComponent(jButtonCustNext)
                    .addComponent(jButtonCustLast)
                    .addComponent(jTextFieldSearchVal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonSearch))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel1)
                    .addComponent(jLabelPOID)
                    .addComponent(jDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2)
                    .addComponent(jLabelStatus))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 435, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonExit)
                    .addComponent(jButtonUpdate)
                    .addComponent(jButtonNewPO)
                    .addComponent(jButtonAddLine)
                    .addComponent(jButtonApprovePO)
                    .addComponent(jButtonProcessPO))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jComboBoxPOPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_jComboBoxPOPopupMenuWillBecomeInvisible
        // TODO add your handling code here:
        String Itm = jComboBoxPO.getSelectedItem().toString();

        for(String s[] : PO){
            if ((s[0] + " - " + s[1]).equals(Itm)) {
                DBA.openDBCon();
                DBA.GetPurchaseOrderData(s[0]);
                DBA.closeDBCon();
            }
        }

        SetData();
}//GEN-LAST:event_jComboBoxPOPopupMenuWillBecomeInvisible

    private void jTablePOMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTablePOMouseClicked
        // TODO add your handling code here:
        if(SwingUtilities.isRightMouseButton(evt)){
            DefaultTableModel tabelModel = (DefaultTableModel)jTablePO.getModel();

            //Get coordinate of mouse click.
            Point p = evt.getPoint();

            rowNumDel = jTablePO.rowAtPoint(p);

            jPopupMenu1.show(evt.getComponent(),evt.getX(),evt.getY());
        }
    }//GEN-LAST:event_jTablePOMouseClicked

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new POFrame().setVisible(true);
            }
        });
    }

    public void RemoveItem(){
        int response = JOptionPane.showConfirmDialog(null,
                "Warning, this will delete row " + Integer.toString(rowNumDel + 1) + ", continue?",
                "Warning",JOptionPane.WARNING_MESSAGE);
        if (response == 0){
            DBA.openDBCon();

            //Read data from Purchase orders and fill in the list.
            DBA.GetPurchaseOrderData(jLabelPOID.getText());

            //Put the POCSV into an array.
            String[] poarry = DBA.POCSV.split(",");

            //Create a new CSV without selected line.
            int count = 0;
            String NewCSV = "";
            while (count<poarry.length){
                if(count != rowNumDel){
                    NewCSV += poarry[count] + ",";
                }
                count++;
            }
            String NCSV = NewCSV.substring(0,NewCSV.length() - 1);

            //Delete Entry from POLines Database.
            String Query = "DELETE FROM POLines WHERE POLID = '" +
                    poarry[rowNumDel] + "'";
            DBA.RunSQLUpdateQuery(Query);

            //Update CSV File for in Purchase Orders.
            Query = "UPDATE PurchaseOrder SET POCSV = '" + NCSV + "' WHERE POID = '" +
                    jLabelPOID.getText() + "'";
            DBA.RunSQLUpdateQuery(Query);

            DBA.closeDBCon();

            LoadTable();
        }
    }

    public void LoadList(){
        //Setup Menu.
        JMenuItem item3 = new JMenuItem("Delete Row");
        item3.setMnemonic('d');
        jPopupMenu1.add(item3);
        item3.addActionListener(
                new ActionListener(){
                    public void actionPerformed(ActionEvent e){
                        RemoveItem();
                    }
                }
        );

        //Remove all items in the combo box.
        jComboBoxPO.removeAllItems();

        DBA.openDBCon();
        PO = DBA.RunSQLQuery("SELECT POID,PODate FROM PurchaseOrder");
        for(String s[] : PO){
            jComboBoxPO.addItem(s[0] + " - " + s[1]);
        }
        DBA.closeDBCon();

        //Get todays date.
        java.util.Date dt = new java.util.Date();
        //java.sql.Date todaysdate = new java.sql.Date( dt.getTime());
        jDateChooser.setDate(dt);

        new Timer().scheduleAtFixedRate(new TimerTask(){
            public void run(){
                RefreshDisp();
            }
        }, 1, 1000);

        LastRecord();
    }

    public void RefreshDisp(){
        if(Global.updateTable){
            Global.updateTable = false;
            LoadTable();
        }
    }
    
    public void SetData(){
        //Make all buttons visible.
        jButtonUpdate.setVisible(true);
        jButtonAddLine.setVisible(true);
        jButtonApprovePO.setVisible(true);
        jButtonProcessPO.setVisible(true);

        //Set status and all available buttons depending on status.
        jLabelPOID.setText(Integer.toString(DBA.POID));
        jDateChooser.setDate(DBA.PODate);
        if(DBA.POState == New){
            //New PO
            jLabelStatus.setText("New Purchase Order");
            jButtonAddLine.setVisible(true);
            jButtonApprovePO.setVisible(true);
            status = New;
        } else {
            jButtonAddLine.setVisible(false);
            jButtonApprovePO.setVisible(false);

            if (DBA.POState == Approved){
                jLabelStatus.setText("PO Approved, Awaiting Order Confirmation");
                status = Approved;
            } else if(DBA.POState == OnOrder) {
                jLabelStatus.setText("PO Ordered");
                status = OnOrder;
            } else if(DBA.POState == Received) {
                jLabelStatus.setText("PO Received");
                status = Received;
            }
        }

        if (status == New){
            jButtonUpdate.setVisible(true);
            jButtonAddLine.setVisible(true);
            jButtonApprovePO.setVisible(true);
            jButtonProcessPO.setVisible(false);
        } else if (status == Approved){
            jButtonUpdate.setVisible(false);
            jButtonAddLine.setVisible(false);
            jButtonApprovePO.setVisible(false);
            jButtonProcessPO.setVisible(true);
        } else if (status == OnOrder){
            jButtonUpdate.setVisible(true);
            jButtonAddLine.setVisible(false);
            jButtonApprovePO.setVisible(false);
            jButtonProcessPO.setVisible(false);
        } else if (status == Received){
            jButtonUpdate.setVisible(false);
            jButtonAddLine.setVisible(false);
            jButtonApprovePO.setVisible(false);
            jButtonProcessPO.setVisible(false);
        }

        LoadTable();

    }

    public void LoadTable(){
        //Initiate a table model and remove all rows.
        DefaultTableModel tabelModel = (DefaultTableModel)jTablePO.getModel();
        for (int x=tabelModel.getRowCount()-1; x>=0; x--){
            tabelModel.removeRow(x);
        }

        DBA.openDBCon();

        //Read data from Purchase orders and fill in the list.
        DBA.GetPurchaseOrderData(jLabelPOID.getText());

        if (!DBA.POCSV.equals("")){

            //Put the POCSV into an array.
            String[] poarry = DBA.POCSV.split(",");
            int count = 0;

            while (count < poarry.length){
                //Read in POLine.
                DBA.GetPOLinesData(poarry[count]);

                //Read in Part Number
                DBA.GetStockCodeData(Integer.toString(DBA.POLPN));

                //Read in appropriate descriptions.
                String Desc = "";
                if(DBA.WHID == 100){
                    DBA.GetMaltData(Integer.toString(DBA.TableID));
                    Desc = DBA.MaltName;
                    //get cost.
                } else if (DBA.WHID == 110){
                    DBA.GetHopsData(Integer.toString(DBA.TableID));
                    Desc = DBA.HopName;
                } else if (DBA.WHID == 120){
                    DBA.GetYeastData(Integer.toString(DBA.TableID));
                    Desc = DBA.YeastDesc;
                } else {
                    DBA.GetSuppliesData(Integer.toString(DBA.TableID));
                    Desc = DBA.SupName;
                }

                DBA.GetVendorData(Integer.toString(DBA.StockVendID));

                //Format Stock Number.
                String StockNumber = String.format("%05d", DBA.POLPN);

                //Calculate extended cost.
                float cost = DBA.POLCost;
                float extcost = cost * (float)DBA.POLQty;

                //Add row to table.
                tabelModel.addRow(new Object[]{count+1,StockNumber,Desc,
                    DBA.VName,DBA.SupNumber,DBA.POLQty,cost,extcost,DBA.WHID,DBA.POLRcvd});

                count++;
            }
        }

        DBA.closeDBCon();
        
    }

    @Action
    public void LastRecord() {
        jComboBoxPO.setSelectedIndex(jComboBoxPO.getItemCount()-1);

        String Itm = jComboBoxPO.getSelectedItem().toString();

        for(String s[] : PO){
            if ((s[0] + " - " + s[1]).equals(Itm)) {
                DBA.openDBCon();
                DBA.GetPurchaseOrderData(s[0]);
                DBA.closeDBCon();
            }
        }

        SetData();
    }

    @Action
    public void FirstRecord() {
        jComboBoxPO.setSelectedIndex(0);

        String Itm = jComboBoxPO.getSelectedItem().toString();

        for(String s[] : PO){
            if ((s[0] + " - " + s[1]).equals(Itm)) {
                DBA.openDBCon();
                DBA.GetPurchaseOrderData(s[0]);
                DBA.closeDBCon();
            }
        }

        SetData();
    }

    @Action
    public void PrevRecord() {
        if(jComboBoxPO.getSelectedIndex()>=1){
            jComboBoxPO.setSelectedIndex(jComboBoxPO.getSelectedIndex()-1);
        }

        String Itm = jComboBoxPO.getSelectedItem().toString();

        for(String s[] : PO){
            if ((s[0] + " - " + s[1]).equals(Itm)) {
                DBA.openDBCon();
                DBA.GetPurchaseOrderData(s[0]);
                DBA.closeDBCon();
            }
        }

        SetData();
    }

    @Action
    public void NextRecord() {
        if(jComboBoxPO.getSelectedIndex() <= (jComboBoxPO.getItemCount()-2)){
            jComboBoxPO.setSelectedIndex(jComboBoxPO.getSelectedIndex()+1);
        }

        String Itm = jComboBoxPO.getSelectedItem().toString();

        for(String s[] : PO){
            if ((s[0] + " - " + s[1]).equals(Itm)) {
                DBA.openDBCon();
                DBA.GetPurchaseOrderData(s[0]);
                DBA.closeDBCon();
            }
        }

        SetData();
    }

    @Action
    public void ExitPO() {
        dispose();
    }

    @Action
    public void NewPO() {
        int response = JOptionPane.showConfirmDialog(null,
                "Warning, this will create a new purchase order, continue?",
                "Warning",JOptionPane.WARNING_MESSAGE);
        if (response == 0){
            DBA.openDBCon();

            //Get todays date.
            java.util.Date dt = new java.util.Date();
            //java.sql.Date todaysdate = new java.sql.Date( dt.getTime());
            jDateChooser.setDate(dt);

            java.util.Date dte = jDateChooser.getDate();
            java.sql.Date PODate = new java.sql.Date( dte.getTime() );

            String fields = "POState,PODate";
            String Ste = "0";
            String query = "'" + Ste + "','" + PODate + "'";
            DBA.RunSQLInsertQuery("PurchaseOrder", fields, query);
            
            jComboBoxPO.removeAllItems();

            PO = DBA.RunSQLQuery("SELECT POID,PODate FROM PurchaseOrder");
            for(String s[] : PO){
                jComboBoxPO.addItem(s[0] + " - " + s[1]);
            }

            DBA.closeDBCon();

            LastRecord();
        }
    }

    @Action
    public void AddLine() {
        if(status == New){
            POLineFrame newFrame = new POLineFrame();
            newFrame.pack();
            newFrame.setLocation(250,250);
            newFrame.setTitle("Add PO Line Item");
            newFrame.setVisible(true);
            newFrame.setIndex(Integer.parseInt(jLabelPOID.getText().trim()));
            newFrame.LoadList();
        }
    }

    @Action
    public void UpdatePO() {
        int response = JOptionPane.showConfirmDialog(null,
                "Warning, this will update the current PO, continue?",
                "Warning",JOptionPane.WARNING_MESSAGE);
        if (response == 0){
            //If Table is still selected, stop selection for update.
            if(jTablePO.isEditing()){
                jTablePO.getCellEditor().stopCellEditing();
            }

            java.util.Date dte = jDateChooser.getDate();
            java.sql.Date PODate = new java.sql.Date( dte.getTime() );

            DBA.openDBCon();

            //Read data from Purchase orders and fill in the list.
            DBA.GetPurchaseOrderData(jLabelPOID.getText());

            //Put the POCSV into an array.
            String[] poarry = DBA.POCSV.split(",");

            //create a boolean to check received status.
            boolean rcvdall = true;

            if(status != OnOrder){
                rcvdall = false;
            }

            //First update PODate if required.
            if (!DBA.PODate.toString().equals(PODate.toString())){
                String Query = "UPDATE PurchaseOrder SET PODate = '" +
                        PODate + "' WHERE POID = '" +
                        jLabelPOID.getText() + "'";
                DBA.RunSQLUpdateQuery(Query);
            }

            //Initiate a table model and remove all rows.
            DefaultTableModel tabelModel = (DefaultTableModel)jTablePO.getModel();
            for (int x=0; x<tabelModel.getRowCount(); x++){
                DBA.GetPOLinesData(poarry[x]);
                //First check if old value was previously approved.
                if(status == New){
                    //Not Approved, it is okay to make changes.
                    //Change qty if appropriate.
                    if(!Integer.toString(DBA.POLQty).equals(tabelModel.getValueAt(x, 5).toString())){
                        String Query = "UPDATE POLines SET POLQty = '" +
                                tabelModel.getValueAt(x, 5).toString() + "' WHERE POLID = '" +
                                poarry[x] + "'";
                        DBA.RunSQLUpdateQuery(Query);
                    }
                    //Change cost if appropriate.
                    if(!Float.toString(DBA.POLCost).equals(tabelModel.getValueAt(x, 6).toString())){
                        String Query = "UPDATE POLines SET POLCost = '" +
                                tabelModel.getValueAt(x, 6).toString() + "' WHERE POLID = '" +
                                poarry[x] + "'";
                        DBA.RunSQLUpdateQuery(Query);
                    }
                } else if(status == OnOrder){
                    //Check Received into stock and and handle quantities in inventory.
                    if(DBA.POLRcvd == false){
                        if(!Boolean.toString(DBA.POLRcvd).equals(tabelModel.getValueAt(x, 9).toString())){
                            String Query = "UPDATE POLines SET POLRcvd = '1' WHERE POLID = '" +
                                    poarry[x] + "'";
                            DBA.RunSQLUpdateQuery(Query);
                            //Call Order Check In Function.
                            CheckIn(DBA.POLPN,DBA.POLQty);
                        }
                    } else if(DBA.POLRcvd == true){
                        if(!Boolean.toString(DBA.POLRcvd).equals(tabelModel.getValueAt(x, 9).toString())){
                            String Query = "UPDATE POLines SET POLRcvd = '0' WHERE POLID = '" +
                                    poarry[x] + "'";
                            DBA.RunSQLUpdateQuery(Query);
                            //Call Order Check In Function.
                            CheckOut(DBA.POLPN,DBA.POLQty);
                        }
                    }
                    //TODO: If all are received, change status.
                    DBA.GetPOLinesData(poarry[x]);
                    if(DBA.POLRcvd == false){
                        rcvdall = false;
                    }
                }
            }

            //if Received all is still true at this point then we need to update status.
            if(rcvdall == true){
                String Query = "UPDATE PurchaseOrder SET POState = '" +
                        Integer.toString(Received)+ "' WHERE POID = '" +
                        jLabelPOID.getText() + "'";
                DBA.RunSQLUpdateQuery(Query);
                DBA.GetPurchaseOrderData(jLabelPOID.getText());
            }
            
            //Close DB Con.
            DBA.closeDBCon();

            //Reload the table.
            LoadTable();
            SetData();
        }
    }

    public void CheckOut(int PartNo, int Qty){
        //Get Stock Code Data.
        DBA.GetStockCodeData(Integer.toString(PartNo));

        //variables for use.
        int qty = DBA.POLQty;
        int tid = DBA.TableID;
        int wid = DBA.WHID;

        if(wid == 100){
            DBA.GetMaltData(Integer.toString(tid));
            float newqty = qty * (float)DBA.MaltBagLbs;
            float newod = DBA.MaltOnOrder + newqty;
            float newoh = DBA.MaltOnHand - newqty;
            String Query = "UPDATE Malt SET MaltOnOrder = '" +
                    Float.toString(newod)+ "', MaltOnHand = '" +
                    Float.toString(newoh)+ "' WHERE MaltID = '" +
                    Integer.toString(tid) + "'";
            DBA.RunSQLUpdateQuery(Query);
        } else if(wid == 110){
            DBA.GetHopsData(Integer.toString(tid));
            float newqty = qty * (float)DBA.HopBagLbs;
            float newod = DBA.HopOnOrder + newqty;
            float newoh = DBA.HopOnHand - newqty;
            String Query = "UPDATE Hops SET HopOnOrder = '" +
                    Float.toString(newod)+ "', HopOnHand = '" +
                    Float.toString(newoh)+ "' WHERE HID = '" +
                    Integer.toString(tid) + "'";
            DBA.RunSQLUpdateQuery(Query);
        } else if (wid > 130){
            DBA.GetSuppliesData(Integer.toString(tid));
            float newqty = qty * (float)DBA.SupQtyPer;
            float newod = DBA.SupOnOrder + newqty;
            float newoh = DBA.SupOnHand - newqty;
            String Query = "UPDATE Supplies SET SupOnOrder = '" +
                    Float.toString(newod)+ "', SupOnHand = '" +
                    Float.toString(newoh)+ "' WHERE SupID = '" +
                    Integer.toString(tid) + "'";
            DBA.RunSQLUpdateQuery(Query);
        }
    }

    public void CheckIn(int PartNo, int Qty){
        //Get Stock Code Data.
        DBA.GetStockCodeData(Integer.toString(PartNo));

        //variables for use.
        int qty = DBA.POLQty;
        int tid = DBA.TableID;
        int wid = DBA.WHID;

        if(wid == 100){
            DBA.GetMaltData(Integer.toString(tid));
            float newqty = qty * (float)DBA.MaltBagLbs;
            float newod = DBA.MaltOnOrder - newqty;
            float newoh = DBA.MaltOnHand + newqty;
            String Query = "UPDATE Malt SET MaltOnOrder = '" +
                    Float.toString(newod)+ "', MaltOnHand = '" +
                    Float.toString(newoh)+ "' WHERE MaltID = '" +
                    Integer.toString(tid) + "'";
            DBA.RunSQLUpdateQuery(Query);
        } else if(wid == 110){
            DBA.GetHopsData(Integer.toString(tid));
            float newqty = qty * (float)DBA.HopBagLbs;
            float newod = DBA.HopOnOrder - newqty;
            float newoh = DBA.HopOnHand + newqty;
            String Query = "UPDATE Hops SET HopOnOrder = '" +
                    Float.toString(newod)+ "', HopOnHand = '" +
                    Float.toString(newoh)+ "' WHERE HID = '" +
                    Integer.toString(tid) + "'";
            DBA.RunSQLUpdateQuery(Query);
        } else if (wid > 130){
            DBA.GetSuppliesData(Integer.toString(tid));
            float newqty = qty * (float)DBA.SupQtyPer;
            float newod = DBA.SupOnOrder - newqty;
            float newoh = DBA.SupOnHand + newqty;
            String Query = "UPDATE Supplies SET SupOnOrder = '" +
                    Float.toString(newod)+ "', SupOnHand = '" +
                    Float.toString(newoh)+ "' WHERE SupID = '" +
                    Integer.toString(tid) + "'";
            DBA.RunSQLUpdateQuery(Query);
        }
    }

    @Action
    public void ApprovePO() {
        int response = JOptionPane.showConfirmDialog(null,
                "Warning, this will approve the current PO, continue?",
                "Warning",JOptionPane.WARNING_MESSAGE);
        if (response == 0){
            if(Global.userPur){
                DBA.openDBCon();
                String Query = "UPDATE PurchaseOrder SET POState = '" +
                        Integer.toString(Approved)+ "' WHERE POID = '" +
                        jLabelPOID.getText() + "'";
                DBA.RunSQLUpdateQuery(Query);
                DBA.GetPurchaseOrderData(jLabelPOID.getText());
                DBA.closeDBCon();

                SetData();
            } else {
                JOptionPane.showMessageDialog(null, "User not approved for this action!",
                        "Error",JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    @Action
    public void ProceessPO() {
        int response = JOptionPane.showConfirmDialog(null,
                "Warning, this will approve the current PO, continue?",
                "Warning",JOptionPane.WARNING_MESSAGE);
        if (response == 0){
            //Update Inventories.
            UpdateInventories();

            //Sort the data into csv by vendor and place state in on order.
            DBA.openDBCon();

            String Query = "UPDATE PurchaseOrder SET POState = '" +
                    Integer.toString(OnOrder)+ "' WHERE POID = '" +
                    jLabelPOID.getText() + "'";
            DBA.RunSQLUpdateQuery(Query);
            DBA.GetPurchaseOrderData(jLabelPOID.getText());

            DBA.closeDBCon();
            //Display order screen.
            ReportFrame newFrame = new ReportFrame();
            newFrame.pack();
            newFrame.setLocation(250,250);
            newFrame.setVisible(true);
            newFrame.setTitle("PO Order Screen");
            newFrame.DisplayPOOrderList(DBA.POCSV);

            
            SetData();
        }
    }

    public void UpdateInventories(){
        DBA.openDBCon();

        //Read data from Purchase orders and fill in the list.
        DBA.GetPurchaseOrderData(jLabelPOID.getText());

        //Put the POCSV into an array.
        String[] poarry = DBA.POCSV.split(",");

        int count = 0;

        while(count < poarry.length){
            //update Inventories accordingly.
            DBA.GetPOLinesData(poarry[count]);
            DBA.GetStockCodeData(Integer.toString(DBA.POLPN));
            
            //variables for use.
            int qty = DBA.POLQty;
            int tid = DBA.TableID;
            int wid = DBA.WHID;

            if(wid == 100){
                DBA.GetMaltData(Integer.toString(tid));
                float newqty = qty * (float)DBA.MaltBagLbs;
                newqty += DBA.MaltOnOrder;
                String Query = "UPDATE Malt SET MaltOnOrder = '" +
                        Float.toString(newqty)+ "' WHERE MaltID = '" +
                        Integer.toString(tid) + "'";
                DBA.RunSQLUpdateQuery(Query);
            } else if(wid == 110){
                DBA.GetHopsData(Integer.toString(tid));
                float newqty = qty * (float)DBA.HopBagLbs;
                newqty += DBA.HopOnOrder;
                String Query = "UPDATE Hops SET HopOnOrder = '" +
                        Float.toString(newqty)+ "' WHERE HID = '" +
                        Integer.toString(tid) + "'";
                DBA.RunSQLUpdateQuery(Query);
            } else if (wid > 130){
                DBA.GetSuppliesData(Integer.toString(tid));
                float newqty = qty * (float)DBA.SupQtyPer;
                newqty += DBA.SupOnOrder;
                String Query = "UPDATE Supplies SET SupOnOrder = '" +
                        Float.toString(newqty)+ "' WHERE SupID = '" +
                        Integer.toString(tid) + "'";
                DBA.RunSQLUpdateQuery(Query);
            }

            count++;
        }

        DBA.closeDBCon();
    }

    @Action
    public void SearchPO() {
        //TODO: Add code to search by specific value.
        String Itm = jTextFieldSearchVal.getText();

        if (!Itm.equals("")){
            for(String s[] : PO){
                if ((s[0] + " - " + s[1]).equals(Itm)) {
                    DBA.openDBCon();
                    DBA.GetPurchaseOrderData(s[0]);
                    DBA.closeDBCon();
                }
            }
            for(String s[] : PO){
                if (s[0].equals(Itm)) {
                    DBA.openDBCon();
                    String selitem = s[0] + " - " + s[1];
                    jComboBoxPO.setSelectedItem(selitem);
                    DBA.GetPurchaseOrderData(s[0]);
                    DBA.closeDBCon();
                    jTextFieldSearchVal.setText("");
                }
            }
            SetData();
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAddLine;
    private javax.swing.JButton jButtonApprovePO;
    private javax.swing.JButton jButtonCustFirst;
    private javax.swing.JButton jButtonCustLast;
    private javax.swing.JButton jButtonCustNext;
    private javax.swing.JButton jButtonCustPrev;
    private javax.swing.JButton jButtonExit;
    private javax.swing.JButton jButtonNewPO;
    private javax.swing.JButton jButtonProcessPO;
    private javax.swing.JButton jButtonSearch;
    private javax.swing.JButton jButtonUpdate;
    private javax.swing.JComboBox jComboBoxPO;
    private com.toedter.calendar.JDateChooser jDateChooser;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabelPOID;
    private javax.swing.JLabel jLabelStatus;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JTable jTablePO;
    private javax.swing.JTextField jTextFieldSearchVal;
    // End of variables declaration//GEN-END:variables

}
